package com.sakiko.controller;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.net.http.HttpResponse;

// 接收 cookie数据
@Controller
@ResponseBody
@RequestMapping("cookie")
public class CookieController {
    /**
     * cookie: 客户端浏览器 【客户端浏览器
     * session: 会话级别的数据共享技术 【服务端服务器  【共享域
     */

    // 需求 1: get /cookie/save  name=root (cookie)
    @GetMapping("save")
    public String save(HttpServletResponse response) {
        Cookie cookie = new Cookie("name", "root");
        response.addCookie(cookie);
        return "cookie save success!!!";
    }

    // 需求 2: get /cookie/show -> name cookie -> 返回给浏览器
    @RequestMapping("show")
    public String show(@CookieValue(name = "name", required = false, defaultValue = "xx") String name) { // 简化 cookie获取
        return name;
    }
//    @RequestMapping("show")
//    public String show(HttpServletRequest request) {
//        Cookie[] cookies = request.getCookies();
//        String value = null;
//        if (cookies != null) {
//            for (Cookie cookie : cookies) {
//                if ("name".equals(cookie.getName())) {
//                    value = cookie.getValue();
//                    break;
//                }
//            }
//        }
//        return value;
//    }

}
